<?php

namespace App\Http\Controllers\Admin;

use App\Model\Carousel;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Config;

use App\Http\Requests\CarouselRequest;

class CarouselController extends Controller
{
    /**
     * @return mixed
     * 轮播图管理
     */
    public function index(){
        $carousel = new Carousel();
        $carouselInfo = $carousel->orderBy('sort','asc')->get();
        return view('admin.carousel.index',['carouselInfo'=>$carouselInfo]);
    }

    /**
     * @param Request $request
     * 异步删除轮播图
     */
    public function delete(Request $request){
        $carousel = new Carousel();
        $id = $request->input("carousel_id");
        $imgurl = $carousel->where('id',$id)->first()->imgurl;
        $res = $carousel->where('id',$id)->delete();
        @unlink('.'.$imgurl);
        if($res){
            echo 1;
        }else{
            echo 0;
        }
    }

    /**
     * @return mixed
     * 新增轮播图
     */
    public function add(){
        return view('admin.carousel.add');
    }
    /**
     * 新增结果
     */
    public function addRes(CarouselRequest $request){
        $carousel = new Carousel();
        $carousel->imgname = $request->input("imgname");
        $carousel->imgurl = substr($this->upImg($request,'pic'),1);
        $res = $carousel->save();
        if($res){
            return redirect('/admin/carousel-list')->with('success','新增成功');
        }else{
            return back()->with('error','新增失败，请稍后再试');
        }
    }
    /**
     * 图片上传
     */
    private function upImg($request,$name){
        if($request->hasFile($name)){
            $path = Config::get('app.carouselImgPath');
            $fileName = time().rand(10000,999999).'.'.$request->file($name)->getClientOriginalExtension();
            $request->file($name)->move($path, $fileName);
            return $path.$fileName;
        }
    }
}
